package org.example.laboratorymanagement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.laboratorymanagement.mapper.DeviceMapper;
import org.example.laboratorymanagement.pojo.Device;
import org.example.laboratorymanagement.pojo.PageBean;
import org.example.laboratorymanagement.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public void delete(List<Integer> ids) {
        deviceMapper.delete(ids);
    }

    @Override
    public void update(Device device) {
        device.setUpdateTime(LocalDateTime.now());
        deviceMapper.update(device);
    }

    @Override
    public void insert(Device device) {
        device.setCreateTime(LocalDateTime.now());
        device.setUpdateTime(LocalDateTime.now());
        deviceMapper.insert(device);
    }

    @Override
    public PageBean pageDevices(Integer page, Integer pageSize, String name, String local) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 查询设备
        List<Device> list = deviceMapper.listDevices(name, local);
        Page<Device> p = (Page<Device>) list;

        // 封装PageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());

        return pageBean;
    }

    @Override
    public void insertBatch(List<Device> devices) {
        // 关闭session的自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            DeviceMapper deviceMapper = sqlSession.getMapper(DeviceMapper.class);
            devices.stream().forEach(device -> deviceMapper.insertBatch(device));
            sqlSession.commit();
        }  catch (Exception e) {
            sqlSession.rollback();
        } finally {
            sqlSession.close();
        }
    }
}
